package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DubboCartServiceImpl implements DubboCartService{

    @Autowired
    private CartMapper cartMapper;

    @Override
    public List<Cart> findCartListByUserId(Long userId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        return cartMapper.selectList(queryWrapper);
    }

    //update tb_cart set num = #{num},updated = #{updated} where user_id=#{userId} and item_id =#{itemId}
    @Override
    @Transactional
    public void updateCartNum(Cart cart) {
        Cart cartTemp = new Cart();
        cartTemp.setNum(cart.getNum());
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("item_id",cart.getItemId())
                     .eq("user_id",cart.getUserId());
        cartMapper.update(cartTemp,updateWrapper);
    }

    //cart对象:{itemId,userId, null...null}
    @Override
    public void deleteCart(Cart cart) {
        //将对象中不为null的条件当做where条件
        cartMapper.delete(new QueryWrapper<>(cart));
    }

    @Override
    @Transactional
    public void saveCart(Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",cart.getUserId())
                    .eq("item_id",cart.getItemId());
        Cart cartDB = cartMapper.selectOne(queryWrapper);
        if(cartDB == null){
            cartMapper.insert(cart);
        }else {
            int num = cart.getNum()+cartDB.getNum();
            Cart cartTemp = new Cart();
            cartTemp.setId(cartDB.getId()).setNum(num);
            cartMapper.updateById(cartTemp);
        }
    }
}
